<template>
  <div class="spider-data">
    <div class="header">
      <h2>爬虫数据管理</h2>
      <div class="header-actions">
        <el-button @click="exportData">
          <el-icon><Download /></el-icon>
          导出数据
        </el-button>
        <el-button type="danger" @click="clearData">
          <el-icon><Delete /></el-icon>
          清空数据
        </el-button>
      </div>
    </div>

    <div class="filter-bar">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input
            v-model="searchText"
            placeholder="搜索数据内容"
            clearable
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-select v-model="taskFilter" placeholder="选择任务" clearable>
            <el-option label="全部任务" value="" />
            <el-option label="新闻爬虫" value="新闻爬虫" />
            <el-option label="商品价格监控" value="商品价格监控" />
            <el-option label="股票数据" value="股票数据" />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-col>
      </el-row>
    </div>

    <el-table :data="filteredData" style="width: 100%" stripe :header-cell-style="{ textAlign: 'center' }" :cell-style="{ textAlign: 'center' }">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="taskName" label="任务名称" width="120" />
      <el-table-column prop="title" label="标题" min-width="200" />
      <el-table-column prop="url" label="源URL" min-width="150">
        <template #default="scope">
          <el-link :href="scope.row.url" target="_blank" type="primary">
            {{ scope.row.url.length > 30 ? scope.row.url.substring(0, 30) + '...' : scope.row.url }}
          </el-link>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.status === 'success' ? 'success' : 'danger'">
            {{ scope.row.status === 'success' ? '成功' : '失败' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="爬取时间" width="160" />
      <el-table-column label="操作" width="150">
        <template #default="scope">
          <el-button size="small" @click="viewDetail(scope.row)">查看</el-button>
          <el-button size="small" type="danger" @click="deleteData(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="totalData"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 数据详情对话框 -->
    <el-dialog
      title="数据详情"
      v-model="showDetailDialog"
      width="800px"
    >
      <div v-if="selectedData">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="任务名称">{{ selectedData.taskName }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="selectedData.status === 'success' ? 'success' : 'danger'">
              {{ selectedData.status === 'success' ? '成功' : '失败' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="标题" :span="2">{{ selectedData.title }}</el-descriptions-item>
          <el-descriptions-item label="源URL" :span="2">
            <el-link :href="selectedData.url" target="_blank" type="primary">
              {{ selectedData.url }}
            </el-link>
          </el-descriptions-item>
          <el-descriptions-item label="爬取时间" :span="2">{{ selectedData.createTime }}</el-descriptions-item>
        </el-descriptions>
        
        <div style="margin-top: 20px;">
          <h4>内容详情：</h4>
          <el-input
            v-model="selectedData.content"
            type="textarea"
            :rows="8"
            readonly
          />
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { Download, Delete, Search } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'

const searchText = ref('')
const taskFilter = ref('')
const dateRange = ref([])
const currentPage = ref(1)
const pageSize = ref(20)
const showDetailDialog = ref(false)
const selectedData = ref(null)

const spiderData = ref([
  {
    id: 1,
    taskName: '新闻爬虫',
    title: '科技创新推动经济发展新动能',
    url: 'https://news.example.com/tech/1',
    content: '随着科技创新步伐的加快，新兴技术正在成为推动经济发展的重要动能...',
    status: 'success',
    createTime: '2024-01-15 10:30:00'
  },
  {
    id: 2,
    taskName: '商品价格监控',
    title: 'iPhone 15 Pro Max 256GB',
    url: 'https://shop.example.com/iphone15',
    content: '商品名称: iPhone 15 Pro Max 256GB, 价格: ¥9999, 库存: 有货',
    status: 'success',
    createTime: '2024-01-15 08:15:00'
  },
  {
    id: 3,
    taskName: '新闻爬虫',
    title: '人工智能在医疗领域的应用前景',
    url: 'https://news.example.com/ai/2',
    content: '人工智能技术在医疗诊断、药物研发等领域展现出巨大潜力...',
    status: 'success',
    createTime: '2024-01-15 09:45:00'
  },
  {
    id: 4,
    taskName: '股票数据',
    title: '腾讯控股 (00700.HK)',
    url: 'https://finance.example.com/00700',
    content: '',
    status: 'failed',
    createTime: '2024-01-14 16:45:00'
  },
  {
    id: 5,
    taskName: '商品价格监控',
    title: 'MacBook Pro 14英寸 M3',
    url: 'https://shop.example.com/macbook',
    content: '商品名称: MacBook Pro 14英寸 M3, 价格: ¥14999, 库存: 缺货',
    status: 'success',
    createTime: '2024-01-14 20:30:00'
  }
])

const filteredData = computed(() => {
  let result = spiderData.value
  
  if (searchText.value) {
    result = result.filter(item =>
      item.title.toLowerCase().includes(searchText.value.toLowerCase()) ||
      item.content.toLowerCase().includes(searchText.value.toLowerCase())
    )
  }
  
  if (taskFilter.value) {
    result = result.filter(item => item.taskName === taskFilter.value)
  }
  
  if (dateRange.value && dateRange.value.length === 2) {
    const [startDate, endDate] = dateRange.value
    result = result.filter(item => {
      const itemDate = item.createTime.split(' ')[0]
      return itemDate >= startDate && itemDate <= endDate
    })
  }
  
  return result
})

const totalData = computed(() => filteredData.value.length)

const viewDetail = (data) => {
  selectedData.value = data
  showDetailDialog.value = true
}

const deleteData = (data) => {
  ElMessageBox.confirm('确定要删除此数据吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const index = spiderData.value.findIndex(item => item.id === data.id)
    if (index > -1) {
      spiderData.value.splice(index, 1)
      ElMessage.success('删除成功')
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

const exportData = () => {
  ElMessage.success('数据导出功能开发中...')
}

const clearData = () => {
  ElMessageBox.confirm('确定要清空所有数据吗？此操作不可恢复！', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    spiderData.value = []
    ElMessage.success('数据已清空')
  }).catch(() => {
    ElMessage.info('已取消操作')
  })
}

const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
}

const handleCurrentChange = (val) => {
  currentPage.value = val
}
</script>

<style scoped>
.spider-data {
  padding: 0;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.filter-bar {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
